Page({
  data: {
    mode: 'pregnancy',
    pregnancyStartDate: '',
    dueDate: '',
    title: '',
    description: '',
    date: '',
    time: ''
  },

  onLoad() {
    // 设置默认日期和时间
    const now = new Date();
    const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000);
    
    const date = tomorrow.toISOString().split('T')[0];
    const time = '12:00';
    
    this.setData({
      date,
      time
    });
  },

  switchMode(e) {
    const mode = e.currentTarget.dataset.mode;
    this.setData({ mode });
  },

  bindPregnancyStartDateChange(e) {
    const pregnancyStartDate = e.detail.value;
    // 计算预产期：末次月经时间 + 280天
    const startDate = new Date(pregnancyStartDate);
    // 确保日期格式为YYYY-MM-DD
    const formattedStartDate = startDate.toISOString().split('T')[0];
    const dueDate = new Date(startDate.getTime() + 280 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
    this.setData({ 
      pregnancyStartDate: formattedStartDate,
      dueDate
    });
    // 立即生成任务
    this.generatePregnancyTasks(formattedStartDate, dueDate);
  },

  bindDueDateChange(e) {
    const dueDate = e.detail.value;
    // 根据预产期反推末次月经时间：预产期 - 280天
    const endDate = new Date(dueDate);
    const pregnancyStartDate = new Date(endDate.getTime() - 280 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
    this.setData({ 
      dueDate: dueDate,
      pregnancyStartDate: pregnancyStartDate
    });
    // 立即生成任务
    this.generatePregnancyTasks(pregnancyStartDate, dueDate);
  },

  generatePregnancyTasks(startDate, dueDate) {
    const pregnancyTasks = [
      {
        week: 6,
        title: '首次产检',
        description: '建立母子健康手册，进行血常规、尿常规、血型、肝肾功能、传染病筛查等检查。'
      },
      {
        week: 11,
        title: 'NT检查',
        description: '进行胎儿颈项透明层厚度检查，筛查染色体异常和先天性心脏病。'
      },
      {
        week: 16,
        title: '唐氏筛查',
        description: '进行血清学唐氏筛查，需空腹检查。'
      },
      {
        week: 20,
        title: '大排畸B超',
        description: '检查胎儿各器官发育情况，测量双顶径、头围、腹围、股骨长等。'
      },
      {
        week: 24,
        title: '糖耐量检查',
        description: '进行75g糖耐量试验，筛查妊娠期糖尿病。'
      },
      {
        week: 28,
        title: '二次产检',
        description: '进行乙肝、梅毒等复查，开始每周自数胎动。'
      },
      {
        week: 32,
        title: '小排畸B超',
        description: '评估胎儿体重和发育状况，开始胎心监护。'
      },
      {
        week: 34,
        title: '产前评估',
        description: '进行骨盆测量，评估分娩方式。'
      },
      {
        week: 36,
        title: '待产准备',
        description: '准备待产包，每周产检、胎心监护，关注宫颈变化。'
      },
      {
        week: 37,
        title: '入产期',
        description: '随时可能临产，注意观察宫缩和见红情况。'
      },
      {
        week: 40,
        title: '预产期',
        description: '达到预产期，准备住院待产。'
      }
    ];

    const startDateTime = new Date(startDate);
    let taskList = wx.getStorageSync('taskList') || [];
    const now = new Date();

    // 移除已有的孕期任务
    taskList = taskList.filter(task => task.type !== 'pregnancy');

    pregnancyTasks.forEach(task => {
      // 根据末次月经时间计算目标日期
      const targetDate = new Date(startDateTime);
      targetDate.setDate(targetDate.getDate() + task.week * 7);
      
      const newTask = {
        id: `pregnancy_${task.week}`,  // 移除时间戳，使ID保持一致
        title: task.title,
        description: task.description,
        targetDate: targetDate.toISOString().split('T')[0],
        createTime: now.toISOString(),
        isRunning: false,
        type: 'pregnancy',
        week: task.week,
        lastPeriodDate: startDate,
        dueDate: dueDate,
        completed: false
      };

      taskList.push(newTask);
    });

    wx.setStorageSync('taskList', taskList);

    wx.showToast({
      title: '已生成孕期提醒',
      icon: 'success',
      duration: 1500
    });

    setTimeout(() => {
      wx.redirectTo({
        url: '/pages/index/index'
      });
    }, 1500);
  },

  bindTitleInput(e) {
    this.setData({
      title: e.detail.value
    });
  },

  bindDescriptionInput(e) {
    this.setData({
      description: e.detail.value
    });
  },

  bindDateChange(e) {
    this.setData({
      date: e.detail.value
    });
  },

  bindTimeChange(e) {
    this.setData({
      time: e.detail.value
    });
  },

  saveTask() {
    if (this.data.mode === 'pregnancy') {
      if (!this.data.pregnancyStartDate || !this.data.dueDate) {
        wx.showToast({
          title: '请选择末次月经时间和预产期',
          icon: 'none'
        });
        return;
      }
      this.generatePregnancyTasks(this.data.pregnancyStartDate, this.data.dueDate);
      return;
    }

    const { title, description, date, time } = this.data;

    if (!title.trim()) {
      wx.showToast({
        title: '请输入事项标题',
        icon: 'none'
      });
      return;
    }

    if (!date || !time) {
      wx.showToast({
        title: '请选择目标日期和时间',
        icon: 'none'
      });
      return;
    }

    const targetDate = new Date(`${date}T${time}:00`);
    const now = new Date();

    if (targetDate <= now) {
      wx.showToast({
        title: '目标时间必须大于当前时间',
        icon: 'none'
      });
      return;
    }

    // 获取现有任务列表
    const taskList = wx.getStorageSync('taskList') || [];

    // 创建新任务
    const newTask = {
      id: Date.now().toString(),
      title,
      description,
      targetDate: targetDate.toISOString(),
      createTime: now.toISOString(),
      isRunning: false,
      type: 'custom'
    };

    // 添加新任务到列表
    taskList.push(newTask);

    // 保存更新后的任务列表
    wx.setStorageSync('taskList', taskList);

    wx.showToast({
  title: '保存成功',
  icon: 'success',
  duration: 1500
});
wx.navigateBack();
  }
});